package com.ai.bmg.bmgwebboot.test.zk;


/**
 * 功能描述
 *
 * @author cWX1142527
 * @since 2023年01月18日
 */
public class Java_862_和至少为k的最短子数组 {
    public static void main(String args[]) {
        int[] nums = new int[]{2,-1,2,6};
        int max = shorttestSubarray(nums,7);
        System.out.println(max);
    }

        public static int shorttestSubarray(int[] nums, int k) {
        // sumNums[i] = sumNums[i - 1] + num[i]
        int[] sumNums = new int[nums.length];
        sumNums[0] = nums[0];
        if (sumNums[0] >= k) return 1;
        int minLength = -1;
        boolean flag = true;
        for (int i = 1; i < nums.length; i++) {
            sumNums[i] = sumNums[i - 1] + nums[i];
            if (sumNums[i] >= k && flag) {
                minLength = i + 1;
                flag = false;
            }
        }
        if (minLength == 1) return 1;
        // (i,j] 之前的和
        for (int i = 0; i < sumNums.length; i++) {
            for (int j = i + 1; j < sumNums.length; j++) {
                if (j - i > minLength && minLength != -1) break;
                if (sumNums[j] - sumNums[i]  >= k) {
                    minLength = minLength == -1 ? j - i : (minLength < j - i ? minLength : j - i);
                }
            }
        }
        return minLength;
    }
}